package com.chezai.client.dao.manager;

import com.chezai.client.bean.RandomPhoto;
import com.chezai.client.dao.DaoManager;
import com.chezai.client.dao.RandomPhotoDao;
import com.chezai.client.global.Const;

import java.util.List;

/**
 * 主要：科一 科四
 * 辅助：科二科三
 * 课程数据操作管理类
 * 课程记录与用户信息关联
 * Created by likunyang on 2017/8/29.
 */

public class RandomPhotoDaoManager {
    private static RandomPhotoDaoManager newInstance;
    private String TAG = this.getClass().getSimpleName();
    private RandomPhotoDao dao;

    private RandomPhotoDaoManager() {
        dao = DaoManager.getInstance().getDaoSession().getRandomPhotoDao();
    }

    public static RandomPhotoDaoManager getInstance() {
        if (newInstance == null) {
            synchronized (RandomPhotoDaoManager.class) {
                if (newInstance == null) {
                    newInstance = new RandomPhotoDaoManager();
                }
            }
        }
        return newInstance;
    }

    public void update(RandomPhoto randomPhoto) {
        dao.update(randomPhoto);
    }

    public RandomPhoto findPeriodRecordPhoto(long _id) {
        return dao.load(_id);
    }

    public long insertRecord(RandomPhoto record) {
        if (record == null)
            throw new IllegalArgumentException(this.getClass().getSimpleName() + " method insertRecord argument record is null");
        record.setUploadStatus(Const.UPLOAD_UNKNOW);
        record.setTryCount(0);
        long id = dao.insert(record);
        return id;
    }

    /**
     * 查找没有照片的记录
     * @param classRecordId 当前课程id
     * @return
     */
    public List<RandomPhoto> findNoHavePhotoPathRecord(long classRecordId) {
        return dao.queryBuilder()
                .where(RandomPhotoDao.Properties.ClassRecordId.eq(classRecordId)
                        , RandomPhotoDao.Properties.UploadStatus.eq(Const.UPLOAD_UNKNOW))
                .list();
    }

    public List<RandomPhoto> findUploadFailedRecord(long classRecordId) {
        return dao.queryBuilder()
                .where(RandomPhotoDao.Properties.ClassRecordId.eq(classRecordId)
                        , RandomPhotoDao.Properties.UploadStatus.eq(Const.UPLOAD_FAILED)
                        , RandomPhotoDao.Properties.TryCount.le(Const.TRY_COUNT))
                .list();
    }

    public List<RandomPhoto> findAllUploadFailedRecord(long classRecordId) {
        return dao.queryBuilder()
                .where(RandomPhotoDao.Properties.ClassRecordId.eq(classRecordId)
                        , RandomPhotoDao.Properties.UploadStatus.eq(Const.UPLOAD_FAILED))
                .list();
    }

    public RandomPhoto findOneUploadFailedRecord(long classRecordId) {
        List<RandomPhoto> list = findAllUploadFailedRecord(classRecordId);
        if (list == null || list.size() == 0) {
            return null;
        } else {
            return list.get(0);
        }
    }
}
